<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表
      type="selection"：表示此列是一个选择框
      @selection-change="selsChange"：对于列表的选择框的值监控事件
    -->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">

      <el-table-column type="selection" width="55">
      </el-table-column>

      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name"  label="部门名称" width="120" >
        <template slot-scope="scope">
          <span @dblclick="popDrawer(scope.$index, scope.row)" v-html="scope.row.name"></span>
        </template>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state == 1">启用</span>
          <span style="color: red" v-else-if="scope.row.state == 0">禁用</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar"> <!--:disabled：是否可以点击
		                                        true：不可选
		                                        false：可选
		                                      -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面
        v-model：在1.X的版本是控制弹出框是否显示的意思，现在是双向绑定
        :visible.sync：控制弹出框是否显示
        :rules="editFormRules"：引用表单校验规则
          prop="name"：表单字段引用表单校验规则中的那个规则，根据名称引用
        ref="editForm"：给当前表单取一个名称，可以通过此名称找到表单
    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理" >
          <!--
            el-select：选择器组件标签
            :key：指定数据中的唯一字段
            :label：用户选中之后回显的值
            :value：用户选中之后要绑定给对象的值，也就是要提交的值
            value-key：如果 Select 的绑定值为对象类型，请务必指定 value-key 作为它的唯一性标识。
          -->
          <el-select clearable v-model="editForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" >
          <div class="block">
            <!--:options="departmentTree"：选中到我们的部门树数据-->
            <el-cascader
                v-model="editForm.parent"
                :options="departmentTree"
                :props="{
                  checkStrictly: true,
                  // 指定value和label去找对象中的那个字段
                  value:'id',
                  label:'name'
                 }"
                clearable></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--抽屉-->
    <el-drawer
        title="我嵌套了表格!"
        :visible.sync="table"
        direction="rtl"
        size="50%">
      <!--列表-->
      <el-table border :data="gridData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">

        <el-table-column type="index" width="60">
        </el-table-column>
        <el-table-column prop="username" label="员工名称" width="100" >
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="160" >
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="160" >
        </el-table-column>
        <el-table-column prop="salt" label="员工盐值" width="180" >
        </el-table-column>
        <el-table-column prop="password" label="员工密码" width="180" >
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="100" >
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template slot="header" slot-scope="scope">
            <el-button type="success" size="small" @click="passStatus(scope.$index, scope.row)">
              新增
            </el-button>
          </template>
          <template  slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      departments: [],
      total: 0, // 总条数
      currentPage: 1, // 页码
      pageSize: 5,
      listLoading: false,
      sels: [],// 列表选中列
      title:"", // 标题
      managers:[], // 所有员工数据
      departmentTree:[], // 部门树数据
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }// trigger: 'blur'：校验方式，失去焦点校验
        ],
        sn: [
          { required: true, message: '请输入部门编号', trigger: 'blur' } // trigger: 'blur'：校验方式，失去焦点校验
        ]
      },
      //编辑界面数据
      editForm: {
        id:null,
        sn:"",
        name:"",
        state:1,
        manager:null,
        parent:null
      },
      table: false,
      dialog: false,
      loading: false,
      gridData: [],
      formLabelWidth: '80px',
      timer: null
    }
  },
  methods: {
    //性别显示转换
    formatSex: function (row, column) {
      return row.state == 1 ? '开启' : row.state == 0 ? '关闭' : '未知';
    },
    handleCurrentChange(val) {
      // 将模型中的当前页数据改变为用户选择的页码
      this.currentPage = val;
      // 分页查询数据函数
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      // 封装接口参数
      let para = {
        // 传递页面
        currentPage: this.currentPage,
        // 传递每页展示条数
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      this.listLoading = true;// 开启忙等
      // 1.发送Axios请求获取到部门分页数据
      this.$http.post("/dept", para)
          .then(result=>{
            // 0.把列表忙等关闭
            this.listLoading = false;
            // 1.将后端返回的分页数据赋值给模型中的departments
            this.departments = result.data.rows;
            // 2.将分页总数赋值给模型中的total
            this.total = result.data.total;
          })
          .catch(result=>{
            console.log(result);
          })

    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; // 开启列表忙等
        // 1.发起请求
        this.$http.delete("/dept/" + row.id)
            .then(result=>{
              this.listLoading = false; // 关闭列表忙等
              if (result.data.success){ // 成功
                // 2.给出成功提示语
                this.$message({
                  message: result.data.msg,
                  type: 'success'
                });
                // 3.设置页码为1
                this.currentPage = 1;
                // 4.查询列表
                this.getDepartments();
              }else { // 失败
                // 2.给出成功提示语
                this.$message({
                  message: result.data.msg,
                  type: 'error'
                });
                // 3.设置页码为1
                this.currentPage = 1;
                // 4.查询列表
                this.getDepartments();
              }
            })
            .catch(result=>{ // 接口调不通
              // 1.关闭忙等框
              this.listLoading = false;
              // 2.给出提示语
              this.$message({
                message: '系统繁忙，请重试！',
                type: 'error'
              });
            })


        /*removeDepartment(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartments();
        });*/
      }).catch(() => { // 取消弹出框

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      // 1.显示修改框
      this.editFormVisible = true;
      // 2.拷贝当前编辑按钮所对应的行的数据到editForm对象中
      this.editForm = Object.assign({}, row);
      // 3.处理parent，变成[2,5,...] // "/2/5/6" [2,5]
      let arr = row.dirPath.split("/") // ['', '2', '5']
      let psion = [];
      for (let i = 1;i < arr.length - 1;i++){
        // parseInt(arr[i])：将字符串转换为int
        psion.push(parseInt(arr[i]));
      }
      this.editForm.parent = psion;
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.editFormVisible = true;
      this.editForm = {
        id:null,
        sn:"",
        name:"",
        state:1,
        manager:null,
        parent:null
      };
    },
    //编辑的提交框
    editSubmit: function () {
      // this.$refs.editForm.validate((valid)：根据表单名称主动使用表单校验进行判断
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            // 1.开启按钮忙等
            this.editLoading = true;
            // 2.拷贝对象
            let para = Object.assign({}, this.editForm);
            // 3.格式化数据，后面我们会在此处改变我们数据的格式
            if(para.parent){ // 当parent不为null的时候再处理
              para.parent = {"id": para.parent[para.parent.length - 1]};
            }
            // 4.发起Axios请求进行保存
            this.$http.put("/dept", para)
                .then(result=>{
                  this.editLoading = false; // 关闭按钮忙等
                  this.editFormVisible = false; // 把新增/修改的模态框关闭
                  if (result.data.success){ // 成功
                    // 2.给出成功提示语
                    this.$message({
                      message: result.data.msg,
                      type: 'success'
                    });
                    // 3.设置页码为1
                    this.currentPage = 1;
                    // 4.查询列表
                    this.getDepartments();
                  }else { // 失败
                    // 2.给出成功提示语
                    this.$message({
                      message: result.data.msg,
                      type: 'error'
                    });
                    // 3.设置页码为1
                    this.currentPage = 1;
                    // 4.查询列表
                    this.getDepartments();
                  }
                })
                .catch(result=>{ // 接口调不通
                  // 1.关闭忙等框
                  this.editLoading = false; // 关闭列表忙等
                  // 2.给出提示语
                  this.$message({
                    message: '系统繁忙，请重试！',
                    type: 'error'
                  });
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      // sels：所有选中数据的对象集合
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      // 将用户选中的所有要删除的对象的id值放入到数组中
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { // 确定
        // 1.开启列表忙等
        this.listLoading = true;
        this.$http.patch("/dept", ids)
            .then(result=>{
              this.listLoading = false; // 关闭列表忙等
              if (result.data.success){ // 成功
                // 2.给出成功提示语
                this.$message({
                  message: result.data.msg,
                  type: 'success'
                });
                // 3.设置页码为1
                this.currentPage = 1;
                // 4.查询列表
                this.getDepartments();
              }else { // 失败
                // 2.给出成功提示语
                this.$message({
                  message: result.data.msg,
                  type: 'error'
                });
                // 3.设置页码为1
                this.currentPage = 1;
                // 4.查询列表
                this.getDepartments();
              }
            })
            .catch(result=>{ // 接口调不通
              // 1.关闭忙等框
              this.listLoading = false;
              // 2.给出提示语
              this.$message({
                message: '系统繁忙，请重试！',
                type: 'error'
              });
            })
      }).catch(() => { // 取消

      });
    },
    search(){
      // 1.把分页页码改变为第一页，否则会有BUG
      this.currentPage = 1;
      // 2.调用查询函数
      this.getDepartments();
    },
    getEmployees(){
      // 1.发送请求获取到所有的员工数据
      this.$http.get("/employee")
          .then(result=>{
            this.managers = result.data;
          })
          .catch(result=>{

          })
    },
    getDepartmentTree(){
      // 1.发送请求获取到所有的员工数据
      this.$http.get("/dept/tree")
          .then(result=>{
            this.departmentTree = result.data;
          })
          .catch(result=>{

          })
    },
    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm('确定要提交表单吗？')
          .then(_ => {
            this.loading = true;
            this.timer = setTimeout(() => {
              done();
              // 动画关闭需要一定的时间
              setTimeout(() => {
                this.loading = false;
              }, 2000);
            }, 2000);
          })
          .catch(_ => {});
    },
    cancelForm() {
      this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    popDrawer(index, row){
      this.$http.get("/employee")
          .then(result =>{
            this.gridData = result.data;
          })
          .catch(result =>{

          })
      // 发送axios请求，得到所有员工数据，赋值给模型中自己设置的字段
      this.table = true;
    }
  },
  mounted() {
    // 调用分页查询部门数据函数
    this.getDepartments();
    // 调用查询所有员工函数
    this.getEmployees();
    // 调用查询部门树数据的函数
    this.getDepartmentTree();
  }
}

</script>

<style scoped>

</style>
